from django import template
register = template.Library()

from django.utils.html import format_html

#自定义分页标签
@register.simple_tag

def ShowPages(count,request):

    p = int(request.GET.get('p',1))
    begin  = p-5
    end = p+4
    if p <6:
        begin = 1
        end = 10 
    if p > (count-4):
        begin = count-9
        end = count
    if count < 10:
        begin = 1
        end = count 

    #获取页面上的其他搜索条件
    data = request.GET.dict()
    data.pop('p',None)
    res = ''
    for k,v in data.items():
        res += '&'+k+'='+v

    ps = ''
    #首页
    ps += '<li><a href="?p=1">首页</a></li>'
    #上一页
    if p > 1:
        ps += '<li><a href="?p='+str(p-1)+res+'">上一页</a></li>'
    for x in range(begin,end+1):
        if p ==x:

            ps += '<li class="am-active"><a href="?p='+str(x)+res+'">'+str(x)+'</a></li>'
        else:
            ps += '<li><a href="?p='+str(x)+res+'">'+str(x)+'</a></li>'
    if p < count:
        ps += '<li><a href="?p='+str(p+1)+res+'">下一页</a></li>'

    ps += '<li><a href="?p='+str(count)+res+'">尾页</a></li>'

    return format_html(ps)


